import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import type { FormInstance } from '@ant-design/pro-components';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { Button, Card, Checkbox, Drawer } from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.module.css';

interface Props {
  title: string;
  data: API.UserDetailInfo;
  readonly: boolean;
  form: FormInstance<any>;
  onClose: () => void;
  open: boolean;
  onFieldsChange?: (changedFields: any, allFields: any) => void;
  onDataChange?: (newData: API.UserDetailInfo) => void;
  onOk: (values: any) => void;
}

export default ({
  title,
  open,
  data,
  readonly,
  form,
  onOk,
  onClose,
  onFieldsChange,
  onDataChange,
}: Props) => {
  // console.log('UserDetailDrawer 接收到的 data:', data);
  // console.log('UserDetailDrawer form对象:', form);

  // 管理每个手机信息的checkbox状态
  const [phoneCheckboxStates, setPhoneCheckboxStates] = useState<{
    [key: string]: {
      brand: boolean;
      price: boolean;
      color: boolean;
    };
  }>({});

  // 当数据变化时，更新checkbox状态
  useEffect(() => {
    if (data?.phones) {
      const newStates: typeof phoneCheckboxStates = {};
      data.phones.forEach((phone, index) => {
        newStates[`phone_${index}`] = {
          brand: !!(phone.ref?.brand || ''),
          price: !!(phone.ref?.price || ''),
          color: !!(phone.ref?.color || ''),
        };
      });
      setPhoneCheckboxStates(newStates);
    }
  }, [data?.phones]);

  // 确保表单正确连接，减少警告
  useEffect(() => {
    if (open && form) {
      // 延迟一帧确保DOM已渲染
      const timer = setTimeout(() => {
        form.validateFields().catch(() => {
          // 忽略验证错误，这只是为了确保表单连接
        });
      }, 0);
      return () => clearTimeout(timer);
    }
  }, [open, form]);

  // 删除手机信息的处理函数
  const handleDeletePhone = (index: number) => {
    const phones = data?.phones || [];
    const updatedPhones = phones.filter((_, i) => i !== index);

    // 清除所有手机相关的表单字段
    const currentValues = form.getFieldsValue();
    const newValues: any = {};

    // 保留非手机字段
    Object.keys(currentValues).forEach((key) => {
      if (!key.startsWith('phone_')) {
        newValues[key] = currentValues[key];
      }
    });

    // 重新设置剩余手机的表单字段
    updatedPhones.forEach((phone, newIndex) => {
      console.log('phone:', phone);

      newValues[`phone_${newIndex}_model`] = phone.phone || '';
      newValues[`phone_${newIndex}_brand`] = phone.ref?.brand || '';
      newValues[`phone_${newIndex}_price`] = phone.ref?.price || '';
      newValues[`phone_${newIndex}_color`] = phone.ref?.color || '';
    });

    form.setFieldsValue(newValues);

    // 通知父组件更新数据
    const newData = {
      ...data,
      phones: updatedPhones,
    };

    if (onDataChange) {
      onDataChange(newData);
    }

    console.log('删除手机信息，索引:', index);
    console.log('更新后的手机列表:', updatedPhones);
  };

  // 新增手机信息的处理函数
  const handleAddPhone = () => {
    const phones = data?.phones || [];
    const newPhone: API.Phone = {
      phone: '',
      ref: {
        brand: '',
        price: 0,
        color: '',
      },
    };
    const updatedPhones = [...phones, newPhone];

    // 通知父组件更新数据
    const newData = {
      ...data,
      phones: updatedPhones,
    };

    if (onDataChange) {
      onDataChange(newData);
    }

    console.log('新增手机信息');
    console.log('更新后的手机列表:', updatedPhones);
  };

  // 提交表单的处理函数
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      console.log('表单提交值:', values);
      // 调用父组件传入的onOk回调函数
      onOk(values);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 渲染手机信息的函数
  const renderPhones = () => {
    const phones = data?.phones || [];

    return (
      <div style={{ marginBottom: 16 }}>
        <label
          style={{ fontWeight: 'bold', marginBottom: 8, display: 'block' }}
        >
          手机信息
        </label>
        {phones.length === 0 ? (
          <div style={{ color: '#999', marginBottom: 12 }}>暂无手机信息</div>
        ) : (
          phones.map((phone, index) => (
            <Card
              key={index}
              title={phone.phone || `手机 ${index + 1}`}
              size="small"
              style={{ marginBottom: 12 }}
              extra={
                !readonly && (
                  <Button
                    type="text"
                    icon={<DeleteOutlined />}
                    size="small"
                    danger
                    onClick={() => handleDeletePhone(index)}
                    title="删除此手机信息"
                  />
                )
              }
            >
              <ProFormText
                name={`phone_${index}_model`}
                label="手机型号"
                readonly={readonly}
              />

              {/* Checkbox 选项行 */}
              {!readonly && (
                <div style={{ marginBottom: 16 }}>
                  <div
                    style={{ display: 'flex', gap: 24, alignItems: 'center' }}
                  >
                    <Checkbox
                      checked={
                        phoneCheckboxStates[`phone_${index}`]?.brand || false
                      }
                      onChange={(e) => {
                        const newStates = {
                          ...phoneCheckboxStates,
                          [`phone_${index}`]: {
                            ...phoneCheckboxStates[`phone_${index}`],
                            brand: e.target.checked,
                          },
                        };
                        setPhoneCheckboxStates(newStates);

                        // 如果取消选中，清空对应的表单值
                        if (!e.target.checked) {
                          form.setFieldValue(`phone_${index}_brand`, '');
                        }
                      }}
                    >
                      品牌
                    </Checkbox>
                    <Checkbox
                      checked={
                        phoneCheckboxStates[`phone_${index}`]?.price || false
                      }
                      onChange={(e) => {
                        const newStates = {
                          ...phoneCheckboxStates,
                          [`phone_${index}`]: {
                            ...phoneCheckboxStates[`phone_${index}`],
                            price: e.target.checked,
                          },
                        };
                        setPhoneCheckboxStates(newStates);

                        // 如果取消选中，清空对应的表单值
                        if (!e.target.checked) {
                          form.setFieldValue(`phone_${index}_price`, '');
                        }
                      }}
                    >
                      价格
                    </Checkbox>
                    <Checkbox
                      checked={
                        phoneCheckboxStates[`phone_${index}`]?.color || false
                      }
                      onChange={(e) => {
                        const newStates = {
                          ...phoneCheckboxStates,
                          [`phone_${index}`]: {
                            ...phoneCheckboxStates[`phone_${index}`],
                            color: e.target.checked,
                          },
                        };
                        setPhoneCheckboxStates(newStates);

                        // 如果取消选中，清空对应的表单值
                        if (!e.target.checked) {
                          form.setFieldValue(`phone_${index}_color`, '');
                        }
                      }}
                    >
                      颜色
                    </Checkbox>
                  </div>
                </div>
              )}

              {/* 输入框分三行显示 */}
              <div>
                {(readonly || phoneCheckboxStates[`phone_${index}`]?.brand) && (
                  <ProFormText
                    name={`phone_${index}_brand`}
                    label="品牌"
                    readonly={readonly}
                    style={{ marginBottom: 16 }}
                  />
                )}
                {(readonly || phoneCheckboxStates[`phone_${index}`]?.price) && (
                  <ProFormText
                    name={`phone_${index}_price`}
                    label="价格"
                    readonly={readonly}
                    style={{ marginBottom: 16 }}
                  />
                )}
                {(readonly || phoneCheckboxStates[`phone_${index}`]?.color) && (
                  <ProFormText
                    name={`phone_${index}_color`}
                    label="颜色"
                    readonly={readonly}
                    style={{ marginBottom: 16 }}
                  />
                )}
              </div>
            </Card>
          ))
        )}
        {!readonly && (
          <Button
            type="dashed"
            icon={<PlusOutlined />}
            onClick={handleAddPhone}
            style={{ width: '100%', marginTop: 8 }}
          >
            新增手机信息
          </Button>
        )}
      </div>
    );
  };

  return (
    <Drawer
      title={title}
      closable={{ 'aria-label': 'Close Button' }}
      width="30%"
      onClose={onClose}
      open={open}
      styles={{
        body: {
          padding: 0,
          height: '100%',
          overflow: 'hidden',
        },
      }}
    >
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
        }}
      >
        <div
          className={styles.customScrollbar}
          style={{
            flex: 1,
            padding: '24px',
            overflowY: 'auto',
          }}
        >
          <ProForm
            key={`form-${data?.id || 'new'}-${open}`}
            form={form}
            readonly={readonly}
            onFinish={onOk}
            onFieldsChange={onFieldsChange}
            submitter={false}
            autoFocusFirstInput={false}
            layout="vertical"
            preserve={false}
            requiredMark={false}
          >
            <ProFormText name="name" label="姓名" />
            {renderPhones()}
          </ProForm>
        </div>

        {/* 底部按钮区域 */}
        <div
          style={{
            padding: '16px 24px',
            borderTop: '1px solid #f0f0f0',
            display: 'flex',
            gap: 8,
            justifyContent: 'flex-end',
          }}
        >
          <Button onClick={onClose}>取消</Button>
          {!readonly && (
            <Button type="primary" onClick={handleSubmit}>
              提交
            </Button>
          )}
        </div>
      </div>
    </Drawer>
  );
};
